import { watch } from 'vue'
let matchMedia
const watchSystemThemeChange = () => {
  // 仅需初始化一次即可
  if (matchMedia) return
  matchMedia = window.matchMedia('(prefers-color-scheme: dark)')
  // 监听主题变更
  matchMedia.onchange = function () {
    changeTheme('system')
  }
}
const changeTheme = (theme) => {
  // html 的 class
  let themeClassName = ''
  switch (theme) {
    case 'light':
      themeClassName = 'light'
      break
    case 'dark':
      themeClassName = 'dark'
      break
    case 'system':
      watchSystemThemeChange()
      themeClassName = matchMedia.matches ? 'dark' : 'light'
      break
  }
  // 修改 html 的 class
  document.querySelector('html').className = themeClassName
}

export default (store) => {
  watch(
    () => store.getters.theme,
    (newVal) => {
      changeTheme(newVal)
    },
    {
      immediate: true
    }
  )
}
